package controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet(urlPatterns = "/upload")
@MultipartConfig
public class UploadController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Part part = request.getPart("myfile");
        String disposition= part.getHeader("Content-Disposition");
        String suffix = disposition.substring(disposition.lastIndexOf("."),disposition.length()-1);
      //  System.out.println(disposition);

        String fileName = "file"+suffix;
        System.out.println(fileName);

        String path= request.getServletContext().getRealPath("upload");
        File pathFile = new File(path);

        System.out.println("path:" + path);

        if(!pathFile.exists()){
            pathFile.mkdir();
        }
        /*
        *  1. 获取输入流
        *  2. 把输出流通过输入流写入服务端文件中
        * */
     //   part.write(path+File.separator+fileName);

        InputStream inputStream= part.getInputStream();

        FileOutputStream fileOutputStream = new FileOutputStream(path+File.separator+fileName);
        int length=0;
        byte [] bytes = new  byte[1024];

        while ((length=inputStream.read(bytes))>0){
            fileOutputStream.write(bytes,0,length);
        }
        inputStream.close();
        fileOutputStream.close();

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
